package com.healthbox.notifications.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.healthbox.notifications.commom.Result;
import com.healthbox.notifications.entity.HealthState;
import com.healthbox.notifications.mapper.HealthStateMapper;
import com.healthbox.notifications.service.HealthStateService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import cn.hutool.core.map.MapUtil;

import javax.annotation.Resource;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chs
 * @since 2022-05-12
 */
@Service
public class HealthStateServiceImpl extends ServiceImpl<HealthStateMapper, HealthState> implements HealthStateService {

    @Resource
    private HealthStateMapper healthStateMapper;

    /**
     * 查看健康状态
     * 函数实现
     * @author chs
     */
    @Override
    public Result getHealthState(String phone) {


            QueryWrapper<HealthState> queryWrapper = new QueryWrapper<>();
            queryWrapper
                    .eq("phoneNum", phone);
            HealthState healthState = healthStateMapper.selectOne(queryWrapper);
            if(healthState==null){
                //为空时第一次访问该页面，往数据库中自动添加该用户对应的健康状态初始记录
                addHealthState(phone);
                return Result.succeed(healthState);
            }else{
                return Result.succeed(healthState);
            }

    }

    /**
     * 变更当前所在地
     * 函数实现
     * @author chs
     */
    @Override
    public Result updateHealthState(HealthState healthState,String phone) {
        if(healthState.getPhoneNum().equals(phone)){
            QueryWrapper<HealthState> queryWrapper = new QueryWrapper<>();
            queryWrapper
                    .eq("phoneNum", phone);
            HealthState needToUpdate = healthStateMapper.selectOne(queryWrapper);
            needToUpdate.setAddress(healthState.getAddress());
            healthStateMapper.updateById(needToUpdate);
            return Result.succeed(needToUpdate);
        }
        else{
            return Result.fail("403","没有权限更改");
        }

    }

    /**
     * 新增健康状态
     * 函数实现
     * @author chs
     */
    @Override
    public Result addHealthState(String phone) {

            QueryWrapper<HealthState> queryWrapper = new QueryWrapper<>();
            queryWrapper
                    .eq("phoneNum", phone);
            HealthState query = healthStateMapper.selectOne(queryWrapper);
            if(query==null){
                HealthState healthState=new HealthState();
                healthState.setPhoneNum(phone);
                healthState.setAddress("未设定");
                healthState.setHealthstate(0);
                healthStateMapper.insert(healthState);
                return Result.succeed(healthState);

            }else{
                return Result.fail("该用户已经存在健康状态");
            }


    }

}
